import { Box } from "@mui/material"
import { useEffect, useState } from "react"
import ArrowRightIcon from '@mui/icons-material/ArrowRight';
import ArrowDropDownIcon from '@mui/icons-material/ArrowDropDown';
import RemoveIcon from '@mui/icons-material/Remove';
import './node.css'
import fetchData from "../../utils/ApiFetch";
import { useNavigate } from "react-router-dom";
const apiUrl = process.env.REACT_APP_API_URL;

function Node(props) {
    const [isOpen, setIsOpen] = useState(props.isOpen === true ? true : false)
    const [childrenNode, setChildrenNode] = useState([])
    const navigate = useNavigate()
    let prefix = null
    if (props.hasChild) {
        if (isOpen) {
            prefix =  <ArrowDropDownIcon/>
        } else {
            prefix = <ArrowRightIcon/>
        }
    } else {
        prefix = <RemoveIcon/>
    }

    useEffect(() => {
        const fetchFiles = async () => {
            try {
                const resp = await fetchData(apiUrl + `/file/getFolderByFid?parentId=${props.id}`);
                console.log(resp);
                setChildrenNode(resp.data.folders)
                if (resp.code === 401) {
                    navigate('/signin')
                    localStorage.removeItem('token')
                } 
            } catch (error) {
                console.log(error);
            }
        }
        if (isOpen && props.hasChild) {
            fetchFiles();
        }
        
    }, [props.id, props.hasChild, isOpen, navigate]);
    
    function handleClick(e, id) {
        e.stopPropagation()
        console.log(`click on id = ${id}`)
        if (props.onSelected) {
            props.onSelected(e, id)
        }
    }

    if (props.childrenNode) {
        setChildrenNode(props.childrenNode.map((e) => <Node key={e.id} onSelected={ele => handleClick(ele, e.id)} hasChild={e.hasChildren} childrenNode={e.childrenNode} name={e.name}/>))
    }

    
    

    let subNode = null;
    if (props.hasChild && isOpen && childrenNode) {
        subNode = <Box sx={{marginLeft:'40px'}}>{ childrenNode.map(node => <Node currentSelected={props.currentSelected} onSelected={props.onSelected} id={node.id} key={node.id} name={node.name} hasChild={node.hasChildren}/>)} </Box> 
    }
    let className = 'folder-node'
    if (props.currentSelected === props.id) {
        className += ' node-selected'
    }

    return (
        <Box > <Box className={className} onClick={e => handleClick(e, props.id)}  sx={{display:'flex', width:'fit-content'}}><div className="prefix" onClick={(e) => { e.stopPropagation(); setIsOpen(!isOpen) }}>{prefix}</div> <span>{props.name}</span></Box>
          { subNode }
        </Box>
    )
}

export default Node
